package com.hackerrank.contests.oct13.challenges.angrychildren2;

import java.util.Arrays;
import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt(), K = in.nextInt();
		long[] c = new long[N], p = new long[N], n = new long[N];
		for(int i = 0; i < N; i++)
			c[i] = in.nextInt();
		Arrays.sort(c);
		for(int i = 1; i < N; i++) {
			p[i] = p[i - 1] + (c[i] - c[i - 1]) * Math.min(i, K - 1);
			if(i >= K)
				p[i] -= c[i - 1] - c[i - K];
		}
		for(int i = N - 2; i >= 0; i--) {
			n[i] = n[i + 1] + (c[i + 1] - c[i]) * Math.min(N - i - 1, K - 1);
			if(N - i - 1 >= K)
				n[i] -= c[i + K] - c[i + 1];
		}
		long d = 0, md;
		for(int i = 0; i < K; i++)
			d += p[i];
		md = d;
		for(int i = K; i < N; i++) {
			d += p[i] - n[i - K];
			if(d < md)
				md = d;
		}
		System.out.println(md);
	}
}
